package com.sinoglobal.shakeprize.fragment;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.sinoglobal.shakeprize.R;
import com.sinoglobal.shakeprize.activity.ShakeActivity;
import com.sinoglobal.shakeprize.bean.CompleteParamer;
import com.sinoglobal.shakeprize.bean.ResponseShakeSessionListItem;
import com.sinoglobal.shakeprize.utils.Contstent;
import com.sinoglobal.shakeprize.utils.OKhttpUtil;
import com.sinoglobal.shakeprize.utils.OKhttpUtil.ResponseCallback;
import com.sinoglobal.shakeprize.utils.SPUtil;
import com.squareup.picasso.Picasso;

import okhttp3.Request;

/**
 * @author temulu
 * @createdate 2015-8-31上午11:21:51
 * @Description
 */
/**
 * @author temulu
 * @createdate 2015-8-31下午5:27:05
 * @Description
 */
@SuppressLint("ValidFragment")
public class SessionItemFragment extends Fragment implements OnClickListener {
	private static final int TIME_CODE = 1;

	private ResponseShakeSessionListItem item;
	private int listSize;
	private TextView iteMainRightNow;// 即将开始/倒计时
	private TextView itemMainHeadTime;// 倒计时时间
	private LinearLayout itemMainHeadNotstarted;// 倒计时容器
	private TextView iteMainHeadStart;// 正在进行
	private TextView itemMainDescriptionText;// 分类
	private TextView itemInfoDescription;// 节目
	private Button itemBtnCurrent;// 马上猛摇
	private Button itemBtnWait;// 提醒我
	private int count;
	private Date date;
	private long systemTime;
	private CompleteParamer paramer;
	private SessionStatus sessionStatus;

	public SessionItemFragment(ResponseShakeSessionListItem sessionListItem,
			int size, long systime, SessionStatus status) {
		super();
		listSize = size;
		item = sessionListItem;
		systemTime = systime;
		sessionStatus = status;
	}

	public void setItem(ResponseShakeSessionListItem item) {
		this.item = item;
	}

	public void setSystemTime(long systime) {
		systemTime = systime;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.shake_session_viewpager_item,
				null);
		ImageView itemMainImage = (ImageView) view
				.findViewById(R.id.shakeSessionItemMainImage);
		itemMainHeadNotstarted = (LinearLayout) view
				.findViewById(R.id.shakeSessionMainHeadNotstarted);
		itemMainHeadTime = (TextView) view
				.findViewById(R.id.shakeSessionMainHeadTime);
		iteMainRightNow = (TextView) view
				.findViewById(R.id.shakeSessionMainHeadText);
		iteMainHeadStart = (TextView) view
				.findViewById(R.id.shakeSessionMainHeadStart);
		itemMainDescriptionText = (TextView) view
				.findViewById(R.id.shakeSessionMainDescriptionText);
		TextView itemInfoDate = (TextView) view
				.findViewById(R.id.shakeSessionInfoDate);
		TextView itemInfoTime = (TextView) view
				.findViewById(R.id.shakeSessionInfoTime);
		itemInfoDescription = (TextView) view
				.findViewById(R.id.shakeSessionInfoDescription);
		itemBtnCurrent = (Button) view
				.findViewById(R.id.shakeSessionBtnCurrent);
		itemBtnWait = (Button) view.findViewById(R.id.shakeSessionBtnWait);
		itemBtnWait.setText("提醒我(" + item.remindNum + ")");
		initTimepiece();
		getSystime();
		itemBtnCurrent.setOnClickListener(this);
		itemBtnWait.setOnClickListener(this);
		if (!item.remind) {
			itemBtnWait.setClickable(item.remind);
			itemBtnWait.setBackgroundResource(R.drawable.shake_pager_number);
		}
		Picasso.with(getActivity()).load(Contstent.PICTURE_PATH + item.roundpic).into(itemMainImage);
		itemInfoDate.setText(handleDate(item.roundstartdate) + "——");
		itemInfoTime.setText(handleDate(item.roundenddate));

		itemMainDescriptionText.setText(item.title);
		itemInfoDescription.setText(item.programname);
		return view;
	}

	/**
	 * 处理场次倒计时状态
	 */
	private void handlerStatus() {
		long difference = item.roundstartdate - systemTime / 1000;
		if (difference <= 0) {
			iteMainHeadStart.setVisibility(View.VISIBLE);
			itemMainHeadNotstarted.setVisibility(View.GONE);
		} else if (difference > 0 && difference <= item.countdown * 60) {
			iteMainHeadStart.setVisibility(View.INVISIBLE);
			itemMainHeadNotstarted.setVisibility(View.VISIBLE);
			itemBtnCurrent.setVisibility(View.INVISIBLE);
			itemBtnWait.setVisibility(View.VISIBLE);
			iteMainRightNow.setText(getResources().getString(
					R.string.shake_text_count_down));
			count = (int) (difference);
			handler.sendEmptyMessage(TIME_CODE);

		} else if (difference > item.countdown * 60) {
			iteMainHeadStart.setVisibility(View.INVISIBLE);
			itemMainHeadNotstarted.setVisibility(View.VISIBLE);
			itemBtnCurrent.setVisibility(View.INVISIBLE);
			itemBtnWait.setVisibility(View.VISIBLE);
			iteMainRightNow.setText(getResources().getString(
					R.string.shake_text_right_now));
			int day = (int) (difference / 60 / 60 / 24);
			int hour = (int) (difference / 60 / 60);
			int minute = (int) (difference / 60);
			if (day > 0) {
				itemMainHeadTime.setText("剩" + day + "天");
			} else if (hour > 0 && hour < 24) {
				itemMainHeadTime.setText("剩" + hour + "小时");
			} else if (minute >= 0 && minute < 60) {
				itemMainHeadTime.setText("剩" + minute + "分钟");
			} else if (difference > 0 && difference < 60) {
				itemMainHeadTime.setText("剩" + (int) difference + "秒");
			}
		}

	}

	/**
	 * 时间戳格式化
	 * 
	 * @param time
	 * @return 返回格式化的时间
	 */
	private String handleDate(long time) {
		date = new Date(time * 1000);
		SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm",
				Locale.CHINA);
		return format.format(date);
	}

	private String handleCountDown(int count) {
		String hours;
		String minutes;
		String seconds;
		int hour = count / (60 * 60);
		int minute = count / 60 % 60;
		int second = count % 60;
		if (hour<10) {
			hours="0"+hour;
		}else {
			hours=""+hour;
		}
		if (minute<10) {
			minutes="0"+minute;
		}else {
			minutes=""+minute;
		}
		if (second<10) {
			seconds="0"+second;
		}else {
			seconds=""+second;
		}
		return hours + ":" + minutes + ":" + seconds;
	}

	@Override
	public void onClick(View arg0) {
		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		if (arg0.getId()==R.id.shakeSessionBtnCurrent) {
			intent.putExtra("roundid", item.roundid);
			intent.putExtra("remianNum", item.remianNum);
			intent.putExtra("size", listSize);
			intent.setClass(getActivity().getApplicationContext(),
					ShakeActivity.class);
			getActivity().getApplication().startActivity(intent);
		}else if (arg0.getId()==R.id.shakeSessionBtnWait) {
			// 发送 提醒我 请求
						remindMe();
		}
	}

	/**
	 * 获取服务端时间
	 */
	private void getSystime() {
		String url = Contstent.SHAKE_PATH + "yaoyiyao/returnTime.do";
		OKhttpUtil.enqueue(url, new ResponseCallback() {

			@Override
			public void onFailure(Request arg0, IOException arg1) {

			}

			@Override
			public void onResponse(String json) throws IOException {
				if (!TextUtils.isEmpty(json)) {
					try {
						paramer = JSONObject.parseObject(json,
								CompleteParamer.class);
					} catch (Exception e) {
						Toast.makeText(getActivity(), "访问超时，请稍后再试", Toast.LENGTH_SHORT).show();
						return;
					}finally{
						handler.removeCallbacksAndMessages(null);
					}
					
					systemTime = paramer.systime;
					initTimepiece();
				}
			}
		});
	}

	/**
	 * 订阅
	 */
	private void remindMe() {
		itemBtnWait.setClickable(false);
		Map<String, Object> request = new HashMap<String, Object>();
		request.put("roundid", item.roundid);
		request.put("productCode", Contstent.PRODUCT_IDENTIFICATION);
		request.put("userId", SPUtil.getString(getActivity(), Contstent.USER_ID));
		String url = Contstent.SHAKE_PATH + "yaoyiyao/saveShaing.do?json="
				+ JSONObject.toJSONString(request);
		OKhttpUtil.enqueue(url, new ResponseCallback() {

			@Override
			public void onFailure(Request arg0, IOException arg1) {
				itemBtnWait.setClickable(true);
			}

			@Override
			public void onResponse(String json) throws IOException {
				itemBtnWait.setClickable(true);
				if (!TextUtils.isEmpty(json)) {
					itemBtnWait.setClickable(false);
					itemBtnWait
							.setBackgroundResource(R.drawable.shake_pager_number);
					item.remindNum++;
					itemBtnWait.setText("提醒我(" + item.remindNum + ")");
					sessionStatus.sessionRemindStatus(false);
				}
			}
		});
	}

	private void initTimepiece() {
		if (systemTime / 1000 < item.roundstartdate) {
			handlerStatus();
		} else {
			itemMainHeadNotstarted.setVisibility(View.GONE);
			iteMainHeadStart.setVisibility(View.VISIBLE);
			itemBtnCurrent.setVisibility(View.VISIBLE);
			itemBtnWait.setVisibility(View.INVISIBLE);
		}
	}

	/** 计时器 */
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case TIME_CODE:
				itemMainHeadTime.setText(handleCountDown(count--));
				if (count < 0) {
					itemMainHeadNotstarted.setVisibility(View.GONE);
					iteMainHeadStart.setVisibility(View.VISIBLE);
					itemBtnCurrent.setVisibility(View.VISIBLE);
					itemBtnWait.setVisibility(View.INVISIBLE);
				}
				postDelayed(new MyRunnable(), 1000);
				break;
			}
		}

	};

	private class MyRunnable implements Runnable {

		@Override
		public void run() {
			handler.sendEmptyMessage(TIME_CODE);
		}

	}

	@Override
	public void onPause() {
		handler.removeCallbacksAndMessages(null);
		super.onPause();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	public interface SessionStatus {

		public void sessionRemindStatus(boolean isRemind);
	}
}
